package com.site.wisdom_construction.util.imgUtil;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/** @Author daiyifei @Date 2021/12/15 @Description */
public class AliyunOSSUtil {

  public static String upload(File file, String Host) {
    String endpoint = OssEntity.getEndpoint();
    String accessKeyId = OssEntity.getKeyId();
    String accessKeySecret = OssEntity.getKeySecret();
    String bucketName = OssEntity.getBucketName();
    String fileHost = Host;

    // 以时间命名图片名称
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    String dateStr = format.format(new Date());

    if (null == file) {
      return null;
    }

    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    try {
      // 容器不存在，就创建
      if (!ossClient.doesBucketExist(bucketName)) {
        ossClient.createBucket(bucketName);
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
        ossClient.createBucket(createBucketRequest);
      }

      String fileUrl = "wisdomConstructionSite/"+fileHost + "/"+dateStr+file.getName().substring(file.getName().indexOf("."));
      // 上传文件
      PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
      // 设置权限 这里是公开读
      ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
      if (null != result) {
        return "https://jjjt.oss-cn-shanghai.aliyuncs.com/"+fileUrl;
      }
    } catch (OSSException oe) {
      oe.printStackTrace();
    } finally {
      // 关闭
      ossClient.shutdown();
    }
    return null;
  }
}
